package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端程序
 */
public class Server {
    public static void main(String[] args)  {

        Server server = new Server();
        try {
            server.fun1();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void fun1() throws IOException {
        //1、创建服务端Socket对象
        ServerSocket ss = new ServerSocket(8080);
        System.out.println("服务端已开启等待客户端连接....");
        while(true){
            //2、获取Socket对象
            Socket socket = ss.accept();
            //获取客户端发送的信息
            String ip = socket.getInetAddress().getHostAddress();
            //创建线程来处理客户端的请求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //3、通过Socket对象获取输入流
                        InputStream in = socket.getInputStream();
                        //4、通过输入流读取内容
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String readLine = br.readLine();
                        System.out.println(ip+":"+readLine);
                        //5、释放资源
                        in.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


}